package com.sm.healthy.base

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.widget.TextView
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.observe
import com.lishuaihua.toast.ToastUtils
import com.sm.healthy.event.AppViewModel
import com.sm.healthy.event.EventViewModel
import com.sm.healthy.ext.dismissLoadingExt
import io.freespiritsocial.user.ext.hideSoftKeyboard
import com.sm.healthy.ext.showLoadingExt
import me.hgj.jetpackmvvm.base.fragment.BaseVmDbFragment
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.getAppViewModel
import me.hgj.jetpackmvvm.ext.util.loge
import me.jessyan.autosize.internal.CustomAdapt

/**
 * 作者　: hegaojian
 * 时间　: 2019/12/21
 * 描述　: 你项目中的Fragment基类，在这里实现显示弹窗，吐司，还有自己的需求操作 ，如果不想用Databind，请继承
 * BaseVmFragment例如
 * abstract class BaseFragment<VM : BaseViewModel> : BaseVmFragment<VM>() {
 */
abstract class BaseFragment<VM : BaseViewModel, DB : ViewDataBinding> : BaseVmDbFragment<VM, DB>(),
    CustomAdapt {

    //Application全局的ViewModel，里面存放了一些账户信息，基本配置信息等
    val appViewModel: AppViewModel by lazy { getAppViewModel<AppViewModel>() }

    //Application全局的ViewModel，用于发送全局通知操作
    val eventViewModel: EventViewModel by lazy { getAppViewModel<EventViewModel>() }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        hideSoftKeyboard(context as Activity)
    }

    /**
     * 当前Fragment绑定的视图布局
     */
    abstract override fun layoutId(): Int


    abstract override fun initView(savedInstanceState: Bundle?)

    /**
     * 懒加载 只有当前fragment视图显示时才会触发该方法
     */
    override fun lazyLoadData() {}

    /**
     * 创建LiveData观察者 Fragment执行onViewCreated后触发
     */
    override fun createObserver() {
        mViewModel.toast.observe(this) {
            it?.let {
                ToastUtils.show(it)
            }
        }
    }

    /**
     * Fragment执行onViewCreated后触发
     */
    override fun initData() {
        mDatabind.setVariable(com.sm.healthy.BR.user, appViewModel)
    }

    /**
     * 打开等待框
     */
    override fun showLoading(message: String) {
        showLoadingExt(message)
    }

    /**
     * 关闭等待框
     */
    override fun dismissLoading() {
        dismissLoadingExt()
    }

    override fun onPause() {
        super.onPause()
        hideSoftKeyboard(activity)
    }

    override fun onDestroyView() {
        this.javaClass.simpleName.loge("csw")
        super.onDestroyView()
    }

    override fun isBaseOnWidth(): Boolean {
        return false
    }

    override fun getSizeInDp(): Float {
        return 600f
    }
}